package logic

import (
	"C/internal/svc"
	"C/models/mysql"
	"C/pkg"
	"C/shenzhousrv"
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"strconv"
)

type AddOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddOrderLogic {
	return &AddOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddOrderLogic) AddOrder(in *shenzhousrv.AddOrderRequest) (*shenzhousrv.AddOrderResponse, error) {
	// todo: add your logic here and delete this line
	var goods mysql.Goods
	err := goods.FindGoods(int(in.GoodsId))
	if err != nil {
		return nil, fmt.Errorf("商品不存在")
	}
	if goods.Stock < int(in.Num) {
		return nil, fmt.Errorf("商品库存不足")
	}
	numbering := uuid.NewString()
	total := goods.Price * float64(in.Num)
	order := mysql.Order{
		UserId:    int(in.UserId),
		Numbering: numbering,
		Total:     total,
		Status:    "待支付",
	}
	err = order.AddOrder()
	if err != nil {
		return nil, fmt.Errorf("生成订单失败")
	}
	orderGoods := mysql.OrderGoods{
		OrderId: int(order.ID),
		GoodsId: int(in.GoodsId),
		Title:   goods.Title,
		Cover:   goods.Cover,
		Price:   goods.Price,
		Num:     int(in.Num),
	}
	err = orderGoods.AddOrderGoods()
	if err != nil {
		return nil, fmt.Errorf("生成订单失败")
	}
	alipay := pkg.Alipay{
		Subject:     goods.Title,
		OutTradeNo:  numbering,
		TotalAmount: strconv.Itoa(int(total)),
	}
	payUrl := alipay.Pay()
	return &shenzhousrv.AddOrderResponse{
		OrderId: int64(order.ID),
		PayUrl:  payUrl,
	}, nil
}
